<?php
namespace app\api\controller;
use app\admin\model\{User,Goods as GoodsModel,StoreOrderStatus,StoreCouponIssue,StoreCategory,GoodsAttr,Order as OrderModel,GoodsCart,UserAddress,StoreCouponUser,GoodsCart as CartModel,OrderCartInfo,GoodsComment,Distributor, UserCertificate,UserMerchant};
use app\Request;
use hg\apidoc\annotation as Apidoc;
use think\facade\Db;
use think\facade\Log;

/**
 * @Apidoc\Title("订单模块")
 */
class Order extends ApiBase{

    /**
     * @Apidoc\Title("确认订单页面")
     * @Apidoc\Url("/api/confirm_order")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("cart_id", type="int",require=true, desc="购物车id 添加购物车接口获得")
     * @Apidoc\Returned("addressInfo", type="object", desc="用户默认地址",
     *      @Apidoc\Returned("id", type="int", desc="地址ID"),    
     *      @Apidoc\Returned("real_name", type="string", desc="收货人"),     
     *      @Apidoc\Returned("phone", type="string", desc="收货电话"),    
     *      @Apidoc\Returned("province", type="string", desc="省份"), 
     *      @Apidoc\Returned("city", type="string", desc="市"), 
     *      @Apidoc\Returned("district", type="string", desc="区"), 
     *     @Apidoc\Returned("detail", type="string", desc="详细地址"), 
     * ),
     * @Apidoc\Returned("cartInfo", type="list[]", desc="购物车详情",
     *          @Apidoc\Returned("id", type="int", desc="购物车id"),   
     *          @Apidoc\Returned("product_attr_unique", type="string", desc="商品唯一标识"),  
     *          @Apidoc\Returned("cart_num", type="int", desc="数量"), 
     *          @Apidoc\Returned("productInfo", type="object", desc="商品详情",
     *                 @Apidoc\Returned("image", type="string", desc="商品图片"),
     *                 @Apidoc\Returned("price", type="string", desc="商品价格"),
     *                 @Apidoc\Returned("ot_price", type="string", desc="商品原价"),
     *                 @Apidoc\Returned("postage", type="string", desc="商品邮费"),
     *                 @Apidoc\Returned("store_name", type="string", desc="商品名称"),
     *          ), 
     *          @Apidoc\Returned("truePrice", type="int", desc="规格商品价格多规则商品已此价格显示"), 
     *          @Apidoc\Returned("thumb", type="string", desc="规格商品图片多规则商品已此图片显示"), 
     * ),
     * @Apidoc\Returned("usableCoupon", type="list[]", desc="可使用优惠券",
     *          @Apidoc\Returned("id", type="int", desc="用户优惠券ID"),
     *          @Apidoc\Returned("cid", type="int", desc="优惠券ID"),
     *          @Apidoc\Returned("coupon_title", type="string", desc="优惠券标题"),
     *          @Apidoc\Returned("coupon_price", type="string", desc="优惠券面额"),
     *          @Apidoc\Returned("use_min_price", type="string", desc="优惠券门槛"),
     *          @Apidoc\Returned("add_time", type="string", desc="领取优惠券开始时间"),
     *          @Apidoc\Returned("end_time", type="string", desc="领取优惠券结束时间")
     *  ),
     * @Apidoc\Returned("unUsableCoupon", type="list[]", desc="不可使用优惠券"),
     * @Apidoc\Returned("priceGroup", type="object", desc="价格组合",
     *              @Apidoc\Returned("priceGroup", type="string", desc="支付价格"), 
     *              @Apidoc\Returned("costPrice", type="string", desc="成本价格")
     * ),
     * @Apidoc\Returned("orderKey", type="string", desc="订单预生成唯一标识"),
     */
    public function confirm(){
        $cart_id = request()->post('cart_id');
        $uid = $this->get_user_id();
        if(!$cart_id) json_response(400,'请提交购买的商品');
         $cartGroup = GoodsCart::getUserProductCartList($uid, $cart_id, 1);
         if (count($cartGroup['invalid'])) json_response(400,$cartGroup['invalid'][0]['productInfo']['store_name'] . '已失效!');
        if (!$cartGroup['valid']) json_response(400,'请提交购买的商品');
          $cartInfo = $cartGroup['valid'];
          $data['addressInfo'] = UserAddress::getUserDefaultAddress($uid);
          $data['cartInfo']    = $cartInfo;
          $priceGroup['totalPrice'] = (float) OrderModel::getOrderSumPrice($cartInfo, 'truePrice');//获取订单总金额
           $priceGroup['costPrice'] = OrderModel::getOrderSumPrice($cartInfo, 'costPrice');//获取订单总成本
           $priceGroup['freight_price'] = OrderModel::calculateShippingFee($cartInfo, $data['addressInfo']);//获取订单总邮费
           $priceGroup['payPrice'] =  $priceGroup['totalPrice']+$priceGroup['freight_price'];//获取订单支付总金额
           $usableCoupons           = StoreCouponUser::getUsableCouponList($uid, $cartGroup, $priceGroup['totalPrice']); //获取用户可使用的优惠券
           $data['usableCoupon']    = $usableCoupons; //可使用优惠券
           $data['unUsableCoupon']  = StoreCouponUser::getUserValidCoupon($uid,array_column($usableCoupons,'id')); //不可使用
          $data['priceGroup'] = $priceGroup; 
           $data['orderKey'] = OrderModel::cacheOrderInfo($uid, $cartInfo, $priceGroup); //缓存订单信息
         json_response(200,'success',$data);
    }

    /**
     * @Apidoc\Title("创建订单")
     * @Apidoc\Url("/api/create_order")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("order_key", type="string",require=true, desc="预生成的订单key")
     * @Apidoc\Param("address_id", type="int",require=true, desc="地址id")
     * @Apidoc\Param("user_coupon_id", type="int", desc="优惠券id")
     * @Apidoc\Returned("js_config", type="object", desc="支付参数",
     *          @Apidoc\Returned ("timeStamp",type="string",desc="时间戳"),
     *          @Apidoc\Returned ("nonceStr",type="string",desc="随机字符串"),
     *          @Apidoc\Returned ("signType",type="string",desc="加密方式"),
     *          @Apidoc\Returned ("paySign",type="string",desc="签名")
     * )
     */
    public function create(){
        $data = request()->post();
        if (!$data['order_key']) json_response(400,'参数错误!');
        // if (!$data['address_id']) json_response(0,'地址不得为空!');
        $data['mark'] = request()->post('mark',''); //订单备注
        $data['user_coupon_id'] = \param_check('user_coupon_id/d','');
        $uid          = $this->get_user_id();
        if (OrderModel::where(['order_id|unique' => $data['order_key'], 'uid' => $uid, 'is_del' => 0])->count()){
            json_response(400 ,'订单已生成');
        }
        $order = OrderModel::cacheKeyCreateOrder($uid, $data['order_key'], $data['address_id'], $data['mark'],$data['user_coupon_id']);
        if(!$order) {
            json_response(400,OrderModel::getErrorInfo());
        }
        $orderId = $order['order_id'];
        $order_key = $data['order_key'];
        $info = compact('orderId', 'order_key');
        if ($orderId) {
            $orderInfo = OrderModel::where('order_id', $orderId)->field('id,paid,pay_price,order_id')->find();
            if (!$orderInfo || !isset($orderInfo['paid'])) json_response(400,'支付订单不存在!');
            if ($orderInfo['paid']) json_response(400,'订单已支付!');
             //支付金额为0
            if (bcsub((float)$orderInfo['pay_price'], 0, 2) <= 0) {
            //创建订单jspay支付
                $payPriceStatus = OrderModel::jsPayPrice($orderId, $uid);
                if ($payPriceStatus)//0元支付成功
                    json_response(200, '微信支付成功', $info);
                else
                    json_response(400, OrderModel::getErrorInfo());
            }else{
                $wechat_server = new \app\common\api\WeChat();
                $jsConfig = $wechat_server->pay_param(User::where('id',$uid)->value('openid'),$orderInfo->order_id,$orderInfo->pay_price*100, str_replace(request()->pathinfo(),'notify',request()->url(true)));
                $info['js_config'] = $jsConfig;
                json_response(200,'success',$info);
            }
        }else{
            json_response(400,'订单生成失败'.OrderModel::getErrorInfo());
        }
    }

    //根据地址重新计算价格
    public function addressComputedOrder()
    {
        $key = \param_check('order_key');
        if (!$key) json_response(0,'参数错误!');
        $address_id = \param_check('address_id',false,'地址不得为空');
        $uid = $this->get_user_id();
        $user_address = UserAddress::where(['id' => $address_id, 'uid' => $uid])->find();
        if(!$user_address) json_response(400,'地址不存在或已删除');
        if (OrderModel::where(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0])->count())
            json_response(400, '订单已生成', ['orderId' => $key, 'key' => $key]);
        $order_cache = OrderModel::getCacheOrderInfo($uid, $key);
        if(!$order_cache) json_response(400,'订单信息已失效，请重新生成订单');
        $priceGroup['totalPrice'] = (float) OrderModel::getOrderSumPrice($order_cache['cartInfo'], 'truePrice');//获取订单总金额
        $priceGroup['costPrice'] = OrderModel::getOrderSumPrice($order_cache['cartInfo'], 'costPrice');//获取订单总成本
        $priceGroup['freight_price'] = OrderModel::calculateShippingFee($order_cache['cartInfo'], $user_address);//获取订单总邮费
        $priceGroup['payPrice'] =  $priceGroup['totalPrice']+$priceGroup['freight_price'];//获取订单支付总金额
        if ($priceGroup)
            json_response(200, 'success', $priceGroup);
        else
            json_response(400,OrderModel::getErrorInfo('计算失败'));
    }

    /**
     * @Apidoc\Title("根据优惠券重新计算订单金额")
     * @Apidoc\Url("/api/order_computed")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("coupon_id", type="string",require=true, desc="用户优惠券id")
     * @Apidoc\Param("key", type="string",require=true, desc="订单key")
     * @Apidoc\Returned("total_price", type="string", desc="订单金额")
     * @Apidoc\Returned("pay_price", type="string", desc="订单支付金额")
     * @Apidoc\Returned("coupon_price", type="string", desc="订单优惠金额")
     */
    public function computedOrder()
    {
        $key = \param_check('key');
        if (!$key) json_response(0,'参数错误!');
        $couppon_id = \param_check('coupon_id');
        $uid = $this->get_user_id();
        if (OrderModel::where(['order_id|unique' => $key, 'uid' => $uid, 'is_del' => 0])->count())
            json_response(400, '订单已生成', ['orderId' => $key, 'key' => $key]);
        $priceGroup = OrderModel::computeOrderPrice($uid, $key, $couppon_id);
        if ($priceGroup)
            json_response(200, 'success', $priceGroup);
        else
            json_response(400,OrderModel::getErrorInfo('计算失败'));
    }


    /**
     * 支付回调
     * @return [type] [description]
     */
    public function notify(){
       $wechat_server = new \app\common\api\WeChat();
       $wechat_server->check_sign(function($data){
            // Db::startTrans();
            try{
                 $order = OrderModel::where('order_id',$data['out_trade_no'])->lock(true)->find();
                 
                 if($order && !$order->paid){
                    $order->paid           = 1;
                    $order->status         = 1;
                    if($order->delivery_type == 3){
                        //数据证书直接是已完成
                        $order->status = 3;
                    }
                    $order->pay_time       = time();
                    $order->transaction_id = $data['transaction_id'];
                    $order->total_fee      = $data['total_fee'];
                    $order->save();
                    $cartInfo =  GoodsCart::where('id','in',$order->cart_id)->select();
                    foreach ($cartInfo as $cart) {
                            //减库存加销量
                        GoodsModel::decProductStock($cart['cart_num'], $cart['product_id'], $cart['product_attr_unique']);
                    }
                    GoodsCart::where('id', 'IN', $order->cart_id)->update(['is_pay' => 1]);
                    $merchant = UserMerchant::where('id',$order->merchant_id)->find();
                    if($merchant){
                        $merchant->amount += $order->pay_price;
                        $merchant->save();
                    }
                    // $distributor = Distributor::checkDistributor($order->did); //检查分销员分销
                    // if($distributor){   
                    //     //是分销员
                    //     OrderModel::create_distributor_order($order->id,$order->did);
                    // }
                }
                StoreOrderStatus::status($order->order_id, 'pay_success', '用户付款成功');
                // Db::commit();
            }catch(\Exception $e){
                Log::error($e->getMessage());
                // Db::rollback();
            }
           
       });
    }

    /**
     * @Apidoc\Title("订单列表")
     * @Apidoc\Url("/api/order_list")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("page", type="int",default=1,desc="	页码 默认1	页码 默认1")
     * @Apidoc\Param("limit", type="int",default=10, desc="	数据量 默认10")
     * @Apidoc\Param("status", type="int", desc="状态0待支付 1待发货 2 待收货 3已收货  4申请退款 5退款通过 6退款未通过 7已评价")
     * @Apidoc\Param("search", type="string", desc="订单号")
     * @Apidoc\Returned("[]", type="list[]", desc="订单列表",
     *          @Apidoc\Returned("add_time", type="string", desc="创建时间"),  
     *          @Apidoc\Returned("order_id", type="string", desc="订单编号"), 
     *          @Apidoc\Returned("pay_price", type="string", desc="支付价格"), 
     *          @Apidoc\Returned("paid", type="支付状态", desc="0 未支付 1已支付"), 
     *          @Apidoc\Returned("cartInfo", type="list[]", desc="订单商品列表",
     *                   @Apidoc\Returned("product_attr_unique", type="string", desc="规格商品唯一值"),  
     *                   @Apidoc\Returned("cart_num", type="int", desc="规格商品数量"), 
     *                   @Apidoc\Returned("suk", type="string", desc="选择的规则"), 
     *                   @Apidoc\Returned("thumb", type="string", desc="规格商品图片"), 
     *                   @Apidoc\Returned("is_reply", type="是否已评价", desc="0未评价 1已评价") 
     *  )
     * )
     */
    public function order_list(){
        $page = request()->param('page/d',1);
        $limit = request()->param('limit/d',10);
        $status = request()->param('status','');
        $search = request()->param('search','');
        $list  = OrderModel::getUserOrderSearchList($this->get_user_id(),$status, $page, $limit, $search);
        json_response(200,'success',$list??[]);
  
    }
    
  /**
     * @Apidoc\Title("订单详情")
     * @Apidoc\Url("/api/order_detail")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("order_sn", type="string",require=true,desc="订单编号")
     * @Apidoc\Returned("order_id", type="string",desc="订单编号")
     * @Apidoc\Returned("real_name", type="string",desc="收货人")
     * @Apidoc\Returned("user_phone", type="string",desc="收货人手机")
     * @Apidoc\Returned("user_address", type="string",desc="收货地址")
     * @Apidoc\Returned("pay_price", type="string",desc="应支付价格")
     * @Apidoc\Returned("deduction_price", type="string",desc="优惠金额")
     * @Apidoc\Returned("pay_time", type="string",desc="支付时间")
     * @Apidoc\Returned("add_time", type="string",desc="创建时间")
     * @Apidoc\Returned("mark", type="string",desc="备注")
     * @Apidoc\Returned("cartInfo", type="list[]",desc="订单商品列表",
     *          @Apidoc\Returned("product_attr_unique", type="string",desc="属性商品唯一值"),    
     *          @Apidoc\Returned("cart_num", type="string",desc="数量"), 
     *          @Apidoc\Returned("truePrice", type="string",desc="价格"), 
     *          @Apidoc\Returned("suk", type="string",desc="所选库存"),
     *          @Apidoc\Returned("thumb", type="string",desc="图片"),
     * )
     * @Apidoc\Returned("productInfo", type="object",desc="通用属性",
     *          @Apidoc\Returned("store_name", type="string",desc="商品名称")
     * )
     */
    public function detail()
    {
        $order_sn = param_check('order_sn');
        $order = OrderModel::getByOrderId($order_sn);
        if (!$order) json_response(0,'订单不存在');
        $order = $order->toArray();
        json_response(200,'success', OrderModel::tidyOrder($order, true, true));
    }



    /**
     * @Apidoc\Title("取消订单")
     * @Apidoc\Url("/api/cancer_order")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("order_id", type="string",require=true, desc="订单编号")
     */
    public function cancel(){
        $order_sn  = param_check('order_sn');
        if(!$order = OrderModel::where(['order_id'=>$order_sn,'uid'=>$this->get_user_id(),'is_del'=>0])->find()) json_response(0,'订单不存在或无法取消');
        if($order->paid==1) json_response(400,'订单已支付，无法取消');
        $order->is_del = 1;
        StoreOrderStatus::status($order->id, 'order_cancel', '用户订单取消');
        if($order->save()) json_response(200,'操作成功');
        json_response(400,'操作失败');
    }

    /**
     * @Apidoc\Title("申请退款")
     * @Apidoc\Url("/api/order_refund")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("order_sn", type="string",require=true, desc="订单编号")
     * @Apidoc\Param("refund_reason_wap_explain", type="string",require=true, desc="退款描述")
     * @Apidoc\Param("refund_reason_wap", type="string",require=false, desc="退款原因")
     * @Apidoc\Param("refund_reason_wap_img", type="string",require=false, desc="退款图片")
     * @Apidoc\Param("refund_express", type="string",require=false, desc="退货物流")
     */
    public function refund(){
        $order_sn = param_check('order_sn');
        $refund_reason_wap_explain = param_check('refund_reason_wap_explain',false,'描述不得为空'); //退款描述
        $refund_reason_wap      = request()->param('refund_reason_wap',''); //退款原因
        $refund_reason_wap_img  = request()->param('refund_reason_wap_img',''); //图片
        $refund_express         = request()->param('refund_express',''); //物流
        if(!$order = OrderModel::where(['order_id'=>$order_sn,'uid'=>$this->get_user_id(),'is_del'=>0])->find()) json_response(400,'订单不存在或无法取消');
        if($order->goods_type == 2){
            json_response(400,'数字产品不能申请退款');
        }
        if(!in_array($order['status'],[1,2,3])) json_response('订单当前无法退款');
        if(in_array($order['status'],[2,3]) && !$refund_express ){
            json_response(400,'请填写物流信息');
        }
        if( $order->take_time > 0 && ((time() - $order->take_time) / (24*60*60)) >7 )  json_response(400,'订单已超时，无法申请退款');
        if($order->refund_price > 0) json_response(400,'已申请过退款了');
        if ($order['paid'] == 0) json_response(400,'订单未支付');
        StoreOrderStatus::status($order['id'], 'apply_refund', '用户申请退款，原因：' . $refund_reason_wap_explain);
        $order->status = 4;
        $order->refund_reason_time          = time();
        $order->refund_reason_wap           = $refund_reason_wap;
        $order->refund_reason_wap_explain   = $refund_reason_wap_explain;
        $order->refund_reason_wap_img       = $refund_reason_wap_img;
        $order->refund_express              = $refund_express;
        $order->refund_price                = $order['pay_price']
        $order->refund_status               = 1;
        if($order->save()) json_response(200,'退款申请成功');
        json_response(400,'退款申请失败');
    }


        /**
     * @Apidoc\Title("已存在订单支付")
     * @Apidoc\Url("/api/order_pay")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("order_sn", type="string",require=true, desc="订单编号")
     * @Apidoc\Returned("js_config", type="object", desc="支付参数",
     *          @Apidoc\Returned ("timeStamp",type="string",desc="时间戳"),
     *          @Apidoc\Returned ("nonceStr",type="string",desc="随机字符串"),
     *          @Apidoc\Returned ("signType",type="string",desc="加密方式"),
     *          @Apidoc\Returned ("paySign",type="string",desc="签名")
     * )
     */
    public function pay(){
        $order_sn = param_check('order_sn');
        $uid      = $this->get_user_id();
        if(!$orderInfo = OrderModel::where(['order_id'=>$order_sn,'uid'=>$uid,'is_del'=>0])->find()) json_response(0,'订单不存在或已经支付');
         if($orderInfo->paid==1) json_response(0,'订单已支付');
         $info['order_id']  = $orderInfo->order_id;
         if (bcsub((float)$orderInfo['pay_price'], 0, 2) <= 0) {
            //创建订单jspay支付
                $payPriceStatus = OrderModel::jsPayPrice($orderInfo->order_id, $uid);
                if ($payPriceStatus)//0元支付成功
                    json_response(200, '微信支付成功', $info);
                else
                    json_response(400, OrderModel::getErrorInfo());
            }else{
                $wechat_server = new \app\common\api\WeChat();
                $jsConfig = $wechat_server->pay_param(User::where('id',$uid)->value('openid'),$orderInfo->order_id,$orderInfo->pay_price * 100, str_replace(request()->pathinfo(),'notify',request()->url(true)));
                $info['js_config'] = $jsConfig;
                json_response(200,'success',$info);
            }
    }



    /**
     * @Apidoc\Title("订单收货")
     * @Apidoc\Url("/api/order_sure")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("order_sn", type="string",require=true, desc="订单编号")
     */
    public function take()
    {
        $order_id = param_check('order_sn');
        if (!$order_id) json_response(400,'参数错误!');
        $res = OrderModel::takeOrder($order_id, $this->get_user_id());
        if ($res) {
            $order_info  = OrderModel::where('order_id', $order_id)->find();
            $gain_coupon = StoreCouponIssue::alias('a')
                ->join('store_coupon b', 'a.cid = b.id')
                ->where('a.status', 1)
                ->where('a.is_full_give', 1)
                ->where('a.is_del', 0)
                ->where('a.full_reduction', '<=', $order_info['total_price'])
                ->sum('b.coupon_price');
                json_response(200,'success',['gain_coupon' => $gain_coupon]);
        } else
            json_response(200,OrderModel::getErrorInfo());
    }

        /**
     * @Apidoc\Title("商品评价")
     * @Apidoc\Url("/api/order_comment")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("unique", type="string",require=true, desc="订单商品标识")
     * @Apidoc\Param("comment", type="string",require=true, desc="评论内容")
     * @Apidoc\Param("pics", type="string",require=true, desc="评论图片 ,号分割")
     */
    public function comment(){
        $unique              = request()->post('unique'); //订单商品标识
        $comment             = request()->post('comment','');
        $level               = request()->post('level',3); //评价等级 1差评 2中评 3好评
        $pics                = request()->post('pics','');
        if(!$unique || !$comment) json_response(400,'缺少参数');
        $cartInfo            = OrderCartInfo::where('unique', $unique)->find();
        $uid                 = $this->get_user_id();
        $user_info           = User::find($uid);
        $group['nickname']   = $user_info['nickname'];
        $group['avatar']     = $user_info['avatar'];
        if (!$cartInfo) json_response(400,'评价产品不存在!');
        $order               = OrderModel::find($cartInfo['oid']);
        if(!$order)    json_response(400,'订单不存在!');
        if($order->paid ==0 || !in_array($order->status,[3,5]))  json_response(400,'当前订单状态不能评价!');
        $orderUid = OrderModel::getOrderInfo($cartInfo['oid'], 'uid')['uid'];
        if ($uid != $orderUid) json_response(400,'评价产品不存在!');
        if (GoodsComment::where(['oid' => $cartInfo['oid'], 'unique' => $unique])->count())
            json_response(0,'该产品已评价!');
        $comment = htmlspecialchars(trim($comment));
        $uniqueList = OrderCartInfo::where('oid', $cartInfo['oid'])->column('unique', 'unique');
        $group   = array_merge($group, [
            'uid'      => $uid,
            'oid'      => $cartInfo['oid'],
            'goods_id' => $cartInfo['product_id'],
            'add_time' => time(),
            'comments' => $comment,
            'images'   => $pics,
            'unique'   => $unique,
            'level'    => $level
        ]);
       $res =  GoodsComment::create($group);
        if($res){
            if (GoodsComment::where('unique', 'IN', $uniqueList)->where('oid', $cartInfo['oid'])->count() == count($uniqueList)) {
                //订单商品都已评价完成
                $order->status   = 7;
                $order->save();
                StoreOrderStatus::status($cartInfo['oid'], 'check_order_over', '用户评价');
            }
        }
        json_response(200,'success');
    }

    /**
     * 评论详情
     *
     * @return void
     */
    public function goods_comments_detail(Request $request){
        $param = $request->getMore([
            ['comment_id', '', 'int'],
        ]);
        if(empty($param['comment_id'])){
            json_response(400,'参数错误');
        }

        if(!$comment = GoodsComment::where('id',$param['comment_id'])->find()) json_response(400,'评论不存在');
        json_response(200,'success',$comment);
    }

    /**
     * 删除评论
     *
     * @return void
     */
    public function goods_comments_delete(Request $request){
        $param = $request->postMore([
            ['comment_id', '', 'int'],
        ]);
        if(empty($param['comment_id'])){
            json_response(400,'参数错误');
        }
        $uid = $this->get_user_id();
        if(!$comment = GoodsComment::where('id',$param['comment_id'])->where('uid',$uid)->find()) json_response(400,'评论不存在或已删除');
        if($comment->delete()){
            json_response(200,'删除成功');
        }else{
            json_response(400,'删除失败');
        }
    }

    /**
     * 证书详情
     *
     * @return void
     */
    public function certificate_detail(){
        $id = param_check('id');
        $certificate = UserCertificate::with(['goods'=>function($query){
            $query->field('id,store_name,store_info,image,description');
        }])->where('order_id',$id)->find();
        if(!$certificate) json_response(0,'证书不存在或已失效');
        json_response(200,'success',$certificate);
    }
    /**
     * 证书生成
     *
     * @return void
     */
    public function certificate_create(){
        $order_sn = param_check('order_sn');
        $certificate_name = request()->param('certificate_name',''); 
        $uid = $this->get_user_id();
        if(!$order = OrderModel::where(['order_id'=>$order_sn,'uid'=>$uid,'is_del'=>0])->find()) json_response(0,'订单不存在或无法生成证书');
        $cartInfo = $order->cartDetail->toArray();
        $goods_info = $cartInfo[0]['cart_info'];
        if($order->paid==0) json_response(400,'订单未支付，无法生成证书');
        if($order->certificate_status ==1) json_response(400,'证书已生成，请勿重复操作');
        $res = OrderModel::createCertificate($order,$certificate_name);
        if($res === false){
            json_response(400,OrderModel::getErrorInfo());
        }
        Db::startTrans();
        try {
            $certificate_url = request()->domain().$res['certificate_path'];
            $order->certificate_url = $certificate_url;
            $order->certificate_status = 1;
            $order->save();
            UserCertificate::create([
                'uid' => $uid,
                'order_id' => $order->id,
                'order_price' => $order->pay_price,
                'goods_id'  => $goods_info['product_id'],
                'certificate_url' => $certificate_url,
                'goods_id' => $goods_info['product_id'],
                'goods_name' => $goods_info['productInfo']['store_name'],
                'goods_thumb' => $goods_info['productInfo']['image'],
                'artist_id' => $goods_info['productInfo']['artist_id'],
                'artist_name' => $goods_info['productInfo']['artist_name'],
                'create_time' => date('Y-m-d H:i:s'),
                'certificate_no' => $res['certificate_no'],
                'certificate_code' => $res['certificate_code'],
            ]);
            Db::commit();
            json_response(200,'生成成功',[
                'certificate_url' => $certificate_url,
                'certificate_no' => $res['certificate_no'],
                'certificate_code' => $res['certificate_code'],
            ]);
        } catch (\Exception $e) {
            Db::rollback();
            json_response(400,'证书生成失败: '.$e->getMessage());
        }


    }
    
    /**
     * 我的数字证书
     *
     * @return void
     */
    public function my_digital_order(){
        $uid = $this->get_user_id();
        $page = request()->param('page/d',1);
        $limit = request()->param('limit/d',10);
        $list = UserCertificate::where('uid',$uid)->order('id desc')->page($page,$limit)->select();
        json_response(200,'success',$list);
    }

    /**
     * 我的证书详情
     *
     * @param [type] $id
     * @return void
     */
    public function my_digital_detail($id){
        $uid = $this->get_user_id();
        if(!$id) json_response(400,'参数错误');
        $info = UserCertificate::where('id',$id)->where('uid',$uid)->find();
        if(!$info) json_response(400,'数字证书不存在');
        json_response(200,'success',$info);
    }
}